package com.luo.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.luo.constant.MessageConstant;
import com.luo.constant.RedisMessageConstant;
import com.luo.entity.Result;
import com.luo.pojo.Member;
import com.luo.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author Zoro
 * @date 2021年08月30
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletResponse response) {
        //2.取出redis里面的验证码和用户输入的验证码进行校验
        String telephone = map.get("telephone").toString();
        String validateCode = map.get("validateCode").toString();
        String redisValidateCode = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_LOGIN + telephone);
        if (!validateCode.equals(redisValidateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //3.如果校验通过
        //判断是否是会员, 不是会员, 自动注册为会员
        Member member = memberService.findByTel(telephone);
        if (member == null) {
            Member newMember = new Member();
            newMember.setPhoneNumber(telephone);
            newMember.setRegTime(new Date());
            memberService.addMember(newMember);
        }
        //保存用户的登录状态( CAS或者自己手动签发token ，我们这里可以使用Cookie存储用户信息)

        Cookie cookie = new Cookie("login_member_telephone", telephone);
        //路径
        cookie.setPath("/");
        //有效期30天（单位秒）
        cookie.setMaxAge(60 * 60 * 24 * 30);
        response.addCookie(cookie);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);

    }
}
